# -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 10:32:33 2017

@author: za-xuzhaoye
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller,coint
import statsmodels.api as sm
import tushare as ts


#mktdata=pd.read_csv('D:\FOF_strategy\A&H_ETF_data\NewData\hgb150176.csv')
mktdata=pd.read_csv('D:\FOF_strategy\A&H_ETF_data\NewData\mktdata.csv')
pclose=mktdata['close']


#mktdata1=pd.read_csv(r"D:\FOF_strategy\A&H_ETF_data\NewData\hs300159919.csv")
mktdata1=pd.read_csv('D:\FOF_strategy\A&H_ETF_data\NewData\mktdata1.csv')
mktdata1.to_csv
pclose1=mktdata1['close']

diff=pclose-pclose1

#协整性检验
def testStationarity(data):
    adftest = adfuller(data)
    result = pd.Series(adftest[0:4], index=['Test Statistic','p-value','Lags Used','Number of Observations Used'])
    for key,value in adftest[4].items():
        result['Critical Value (%s)'%key] = value
    return result

zz=pd.concat([testStationarity(pclose),testStationarity(pclose1)],axis=1)
zz.columns=['hxzxb','nfxg']


diff_etf = pclose.diff(1)
diff_etf.dropna(inplace=True)
diff_etf=np.array(diff_etf)

diff_etf1 = pclose1.diff(1)
diff_etf1.dropna(inplace=True)
diff_etf1=np.array(diff_etf1)
tz=pd.concat([testStationarity(diff_etf),testStationarity(diff_etf1)],axis=1)
tz.columns=['hxzxb','nfxg']

coint_test= coint(pclose,pclose1)[1]

#OLS
x=pclose1
y=pclose
X=sm.add_constant(x)
result=(sm.OLS(y,X)).fit()
print(result.summary())

#基于513600恒指etf 和 513660恒生通的套利策略
#mean=(hstetf1-1.0316*hzetf1).mean()
#std=(hstetf1-1.0316*hzetf1).std()
mean=(pclose-pclose1).mean()
std=(pclose-pclose1).std()
up=mean+std
down=mean-std
s1=pd.Series(mean,index=range(len(pclose)))
up_line=pd.Series(up,index=range(len(pclose)))
down_line=pd.Series(down,index=range(len(pclose)))
data3=pd.concat([pclose-pclose1,s1,up_line,down_line],axis=1)
data3.columns=['spreadprice','mean','upper','down']
print "UP is "+str(up),"down is "+str(down),"STD is "+str(std)

data3.plot(figsize=(15,7))

#tdbook,sgn_long,sgn_short=backtest(marketdata,sgn_long,sgn_short)